//
//  MeBillViewController.m
//  RainbowFM
//
//  Created by jv on 14-12-13.
//  Copyright (c) 2014年 RB. All rights reserved.
//

#import "MeBillViewController.h"
#import "OrderModel.h"
#import "UtilsCell.h"
#import "PayViewController.h"
#import "MeBillDetailViewController.h"

@interface MeBillViewController ()<UIAlertViewDelegate>{
    NSMutableArray *listArray;
    OrderListItem *checkItem;
}

@end

@implementation MeBillViewController

-(void)fetchListData{
    [listArray removeAllObjects];
    [[OrderModel sharedModel] fetchUserOrderListWithStatus:@"" currentPage:@"1" result:^(BOOL success, NSArray *array, NSString *msg) {
        [listArray addObjectsFromArray:array];
        [self.tableView reloadData];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    listArray = [NSMutableArray array];
    
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self fetchListData];
}

-(NSString *)timeAndDateStringFromTimeInterval:(long long int)timeInterval{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    NSString *timeString = [dateFormatter stringFromDate:date];
    
    return timeString;
}

#pragma mark - table datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderListCell" forIndexPath:indexPath];
    OrderListItem *item = listArray[indexPath.row];
    
    cell.merchantNameLabel.text = item.merchantName;
    cell.prodName.text = item.prodName;
    cell.orderDateLabel.text = [self timeAndDateStringFromTimeInterval:[item.orderDate longLongValue]];
    [cell.prodImageView sd_setImageWithURL:[NSURL URLWithString:item.prodImg]];
    cell.priceLabel.text = _RMB(item.prodTotalPrice);
    cell.confirmButton.tag = indexPath.row;
    cell.cancelButton.tag = indexPath.row;
    [cell.confirmButton addTarget:self action:@selector(confirmAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.cancelButton addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell cellStatus:item];

    return cell;
}



-(void)confirmAction:(UIButton *)button{
    checkItem = listArray[button.tag];
    if ([checkItem.orderStatus integerValue] == 1) { //付款
        [[OrderModel sharedModel] paymentWithOrderID:checkItem.orderId payType:@"aliPay" result:^(BOOL success, NSString *payURL, NSString *msg) {
            PayViewController *payView = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"PayViewController"];
            payView.payURL = payURL;
            [self.navigationController pushViewController:payView animated:YES];
        }];
    }
    
    else if([checkItem.orderStatus integerValue] == 4){ //申请退款
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"退款" message:@"退款理由:" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
        [alertView show];
    }
    
    else if([checkItem.orderStatus integerValue] == 5){ //确认收货
        [[OrderModel sharedModel] receiptOrderWithOrderID:checkItem.orderId result:^(BOOL success, NSString *msg) {
            if (success) {
                [self fetchListData];
            }
        }];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        UITextField *textField_ = [alertView textFieldAtIndex:0];
        [[OrderModel sharedModel] refundOrderWithOrderID:checkItem.orderId desc:textField_.text result:^(BOOL success, NSString *msg) {
            if(success){
                [self fetchListData];
                [SVProgressHUD showSuccessWithStatus:msg];
            }else{
                [SVProgressHUD showErrorWithStatus:msg];
            }
        }];
    }
}


-(void)cancelAction:(UIButton *)button{
    OrderListItem *item = listArray[button.tag];
    if ([item.orderStatus integerValue] == 1) { //取消订单
        [SVProgressHUD show];
        [[OrderModel sharedModel] cancelOrderWithOrderID:item.orderId result:^(BOOL success, NSString *msg) {
            if (success) {
                [self fetchListData];
                [SVProgressHUD showSuccessWithStatus:msg];
            }else{
                [SVProgressHUD showErrorWithStatus:msg];
            }
        }];
    }
    
    else if([item.orderStatus integerValue] == 5){//延迟收货
        [[OrderModel sharedModel] delayOrderWithOrderID:item.orderId result:^(BOOL success, NSString *msg) {
            if (success) {
                [self fetchListData];
                [SVProgressHUD showSuccessWithStatus:msg];
            }else{
                [SVProgressHUD showErrorWithStatus:msg];
            }
        }];
        
    }
}

#pragma mark - table delegate



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    MeBillDetailViewController *meBillDetailView = [self.storyboard instantiateViewControllerWithIdentifier:@"MeBillDetailViewController"];
    meBillDetailView.orderListItem = listArray[indexPath.row];
    [self.navigationController pushViewController:meBillDetailView animated:YES];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
